import React from 'react';
import { inject, observer} from 'mobx-react';
import {WeaLocaleProvider,WeaButton,WeaTableEditable} from 'ecCom';
import { Button, Tooltip, Spin, Calendar, message} from 'antd';
import { toJS } from 'mobx';
import * as myWorkPlanApi from '../../apis/myWorkPlan';
import * as staffkanbanApi from '../../apis/staffKanban';
import DatePicker from '../../components/myWorkPlan/rightContainer/rightTab/datePicker/DatePicker';
import Rightcontainer from '../../components/myWorkPlan/rightContainer/index';
import '../../lib/wdCalendar_lang_wev8';
const ButtonGroup = Button.Group;
const getLabel = WeaLocaleProvider.getLabel;
const allStores = ['staffKanbanStore','myWorkPlanStore'];
@inject(...allStores)
@observer
export default class RightContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      date: new Date(),
      eid: window.location.hash.split('?eid=')
    }
  }

  componentWillMount() {
    // const { getCalendarBaseData } = this.props.staffKanbanStore;
    // getCalendarBaseData();
  }

  componentDidMount() {
    let { query = false} = this.props;
    let p1 = staffkanbanApi.getCalendarBaseData();
    Promise.all([p1]).then(res => {
      const {rightStatus,DATA_FEED_URL,dialogHeight,getMySubs,defaultkey,setRightStatus,setState} = this.props.staffKanbanStore;
      const {timeType,defBgTime, defEdTime, defBgTimeStr, defEdTimestr,zone_offset,weekstartday} = toJS(rightStatus);
      //获取客户端时区
      const clientTimeZone = new Date().getTimezoneOffset()/60;
      let millTime = new Date().getTime();
      if(zone_offset !== (-clientTimeZone)){
        millTime = millTime + (clientTimeZone+zone_offset)*60*60*1000;
      }
      let tempArr = [];
      let tempId = [];
      tempArr.push(res[0].name);
      tempId.push(res[0].id);
      let op = {
        view: timeType,//指定显示的视图（周，月，日）
        theme: 1,//指定默认模板，比如拖拽新建日程时日程的颜色
        showday: new Date(millTime),//指定显示的日期，在视图中显示的日， 周，月为当前指定日期所在的日，周，月。
        DeleteCmdhandler: () => { },//删除日程的回调函数
        EditCmdhandler: (e) => {  },//编辑日程的回调函数
        ViewCmdhandler: (e) => { },    //查看日程的回调函数
        autoload: true,
        defBgTime: defBgTime,
        defEdTime: defEdTime,
        defBgTimeStr: defBgTimeStr,
        defEdTimestr: defEdTimestr,
        selectedUser: '',//指定当前选定的人员
        isShare: 2,//（isShare：1 显示“所有日程”，其他：显示“我的日程”
        workPlanType: '',//日程类型默认为全部，全部传空
        url: DATA_FEED_URL + "?method=list&selectUser=",  //视图中日程项数据请求url
        quickAddHandler: true,
        doGetData: () => { this.getData(res[0].id)},
        newData: '',
        canSave: false,
        weekstartday: res[0].weekStartDay,
      };
      let _MH = document.documentElement.clientHeight;//浏览器高度
      let _dvH = _MH - 144 + 8 - 67 + 30 + 8;//144为上面的height,67为ecology系统菜单
      if(window.location.href.indexOf("/spa/workplan/static/index")>-1||window.location.href.indexOf("/#/")>-1){
          _dvH = _MH -144 + 8 + 30 + 8;
      }
      op.height = _dvH;
      if(dialogHeight>0){
        op.height =dialogHeight;
      }
      // 初始化基础数据
      setState({defaultkey: res[0].id,selectKeyArr: tempId, defaultHrm: tempArr, selectHrmStr: tempArr});
      setRightStatus({weekstartday: res[0].weekStartDay,}); 
      jQuery("#gridcontainer").bcalendar(op);
    });
    ;
  }


  componentWillReceiveProps(nextProps) {
    // 和左侧通信
    let {selectKeyArr, rightStatus} = nextProps.staffKanbanStore;
    const {date} =  toJS(rightStatus);
    selectKeyArr = toJS(selectKeyArr);
    if(selectKeyArr[0] && selectKeyArr[0] != '') {
      this.doRefreshCalender('', '-9900', selectKeyArr, false, date, true,)
    }
  }

  doRefreshCalender = (data, selected, selectedUser, canSave = false, date, canLoad, type) => {//第一个参数data为（data数据），selected为日程类型，初始化传空，之后传该值,canSave是否可以保存
    const {rightStatus,DATA_FEED_URL,dialogHeight} = this.props.staffKanbanStore;
    let {timeType,defBgTime, defEdTime, defBgTimeStr, defEdTimestr,zone_offset,weekstartday} = toJS(rightStatus);
    selected = selected == '-9900' ? '' : selected;
    timeType = timeType == '' ? 'week' : timeType;
    //获取客户端时区
    let millTime = new Date(date).getTime();
    if(typeof(date)==='string'){
      const clientTimeZone = new Date().getTimezoneOffset()/60;
      if(zone_offset !== (-clientTimeZone)){
        millTime = millTime + (clientTimeZone+zone_offset)*60*60*1000;
      }
    }
    
    let op = {
      view: type ? type : timeType,//指定显示的视图（周，月，日）
      theme: 1,//指定默认模板，比如拖拽新建日程时日程的颜色
      showday: new Date(millTime),//指定显示的日期，在视图中显示的日， 周，月为当前指定日期所在的日，周，月。
      DeleteCmdhandler: () => { },//删除日程的回调函数
      EditCmdhandler: (e) => { },//编辑日程的回调函数
      ViewCmdhandler: (e) => { },//查看日程的回调函数
      autoload: false,
      canLoad: canLoad,    
      defBgTime: defBgTime,
      defEdTime: defEdTime,
      defBgTimeStr: defBgTimeStr,
      defEdTimestr: defEdTimestr,
      selectedUser: selectedUser,//指定当前选定的人员
      isShare: 2,//（isShare：1 显示“所有日程”，其他：显示“我的日程”
      workPlanType: selected,
      quickAddHandler: true,
      url: DATA_FEED_URL + "?method=list&selectUser=",  //视图中日程项数据请求url
      doGetData: () => { this.getData(selectedUser) },//E9获取数据的接口
      newData: data,//E9data数据
      canSave: canSave,//E9是否将数据渲染到页面
      doDrog: (params) => { },//拖动实现编辑
      weekstartday: weekstartday,//日历从周几开始，0为周日，1为周一
    };
    let _MH = document.documentElement.clientHeight;
    // let _MH = jQuery("#workPlan-myWorkPlan-id").height();

    let _dvH = _MH - 144 + 8 +8 + 30 + 8;//144为上面的height,67为ecology系统菜单
    if(window.location.href.indexOf("/spa/workplan/static/index")>-1||window.location.href.indexOf("/#/")>-1){
      _dvH = _MH -144 + 8 + 30 + 8;
    }
    op.height = _dvH;
   
    if(dialogHeight>0){
      op.height =dialogHeight-144 + 8;
    }
    jQuery("#gridcontainer").BcalSetOp(op);
    canLoad && this.getData(selectedUser)
  }

  changeDateFormat = data => {
    if (typeof (data) === 'string' && data != '') {
      return data
    }
    //日期格式转为yyyy-MM-dd
    let now = data || new Date();
    let year = now.getFullYear();
    let month = (now.getMonth() + 1).toString();
    let day = (now.getDate()).toString();
    if (month.length == 1) {
      month = "0" + month;
    }
    if (day.length == 1) {
      day = "0" + day;
    }
    let dateString = year + "-" + month + "-" + day;
    return dateString;
  }

  changeTimeType = (type) => {
    const {setRightStatus,rightStatus,selectKeyArr} = this.props.staffKanbanStore;
    const {date} =  toJS(rightStatus);
    if(type) {
      setRightStatus({timeType: type});
      this.doRefreshCalender('', '-9900', selectKeyArr, false, date, true, type)
    }
  }

  getData = (selectedUser) => {
    ///////////////////////
    const {eid} = this.state;
    const {setState,rightStatus,getCalendarDatas,setRightStatus} = this.props.staffKanbanStore;
    const {date,timeType} = toJS(rightStatus);
    let viewType = timeType == 'day' ? 1 : timeType == 'week' ? 2 : 3
    let params = {
      hrmId: selectedUser,
      selectDate: this.changeDateFormat(date),
      isCalendar: '1',
      viewType: viewType,
      eid: eid.length>1?eid[1]:'',
    }
    if(eid.length==1) {
      message.error(getLabel(505882,'eid为空！') );
    }
    setState({spinning: true});
    staffkanbanApi.getCalendarDatas(params).then((result) => {
      setState({spinning: false});
      // setRightStatus({weekstartday: result.weekstartday});
      result.events && result.events.map(c => {
        c[1] = c[1].replace(/>/g,' ');
      });
      $("#gridcontainer").BcalSetDate(result);
    });
  
  }

  changeDateFormat = data => {
    if (typeof (data) === 'string' && data != '') {
      return data
    }
    //日期格式转为yyyy-MM-dd
    let now = data || new Date();
    let year = now.getFullYear();
    let month = (now.getMonth() + 1).toString();
    let day = (now.getDate()).toString();
    if (month.length == 1) {
      month = "0" + month;
    }
    if (day.length == 1) {
      day = "0" + day;
    }
    let dateString = year + "-" + month + "-" + day;
    return dateString;
  }

  changePicker = (momentValue,value) => {
    const {setRightStatus,selectKeyArr} = this.props.staffKanbanStore;
    let valuestr = (value instanceof Array) ? value[0] : value;
    this.setState({date: momentValue});
    setRightStatus({date: valuestr});
    this.doRefreshCalender('', '-9900', selectKeyArr, false, valuestr, true)
  }

  getReload = (type) => {
    const {setRightStatus,rightStatus,selectKeyArr} = this.props.staffKanbanStore;
    const {date} = toJS(rightStatus);
    if(type === 'current') {
      let datestr = this.changeDateFormat(new Date())
      setRightStatus({date: new Date()});
      this.doRefreshCalender('', '-9900', selectKeyArr, false, datestr, true)
    }
    if(type === 'refresh') {
      this.doRefreshCalender('', '-9900', selectKeyArr, false, date, true)
    }
  }

  getRightTopTab = () => {
    const {rightStatus} = this.props.staffKanbanStore;
    const {timeType,date,weekstartday} = toJS(rightStatus);
    let field = [];
    let name = '';
    if(timeType=='week')name=`${getLabel(15539,'本周')}`
    if(timeType=='month')name=`${getLabel(15541,'本月')}`
    if(timeType=='day')name=`${getLabel(15537,'今天')}`
    field.push(
      <div className='rightcontainer-top-tab'>
        <ButtonGroup ecId={`${this && this.props && this.props.ecId || ''}_ButtonGroup@8lnoia@topTab`} >
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@c9ly2a@day`} type={timeType=='day'?'primary':'ghost'}  onClick={()=>this.changeTimeType('day')}>{getLabel(390,'日')}</Button>
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8zwx54@week`} type={timeType=='week'?'primary':'ghost'} onClick={()=>this.changeTimeType('week')}>{getLabel(1926,'周')}</Button>
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@am33j8@month`} type={timeType=='month'?'primary':'ghost'} onClick={()=>this.changeTimeType('month')}>{getLabel(33452,'月')}</Button>
        </ButtonGroup>
        <DatePicker ecId={`${this && this.props && this.props.ecId || ''}_DatePicker@o6i20e@changePicker`} type={timeType} className="picker" date={date} weekstartday={weekstartday} onChange={this.changePicker}/>
        {<WeaButton ecId={`${this && this.props && this.props.ecId || ''}_WeaButton@3mhq50@current`} type="ghost" text={name} disabled={false} onClick={() => {this.getReload('current')}} /> }
        <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@6j9im4@refresh`} placement="bottom" title={getLabel(354,'刷新')} onClick={() => {this.getReload('refresh')}}>
          <span className="icon-coms-Refresh doreload"  onClick = {() => {}}></span>
        </Tooltip>
      </div>
    );
    return field;
  }

  getContent = () => {
    let field = [];

    field.push(
      <div className="rightcontainer-content" id='gridcontainer'>
      </div>
    );

    return field;
  }

  render() {
    const {spinning,selectKeyArr} = this.props.staffKanbanStore;

    return(
      <div className='staff-kanban-rightcontainer'>
        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@clmbjz`} spinning={spinning}>
          {this.getRightTopTab()}
          {/* <Rightcontainer /> */}
          {this.getContent()}
        </Spin>
      </div>
    );
  }
}